import axios from 'axios'
//具体封装请求的方法
const key = 'b0ed3d91a25e8351ac877bd6c133e160'
const url = `https://restapi.amap.com/v3/weather/weatherInfo?key=${key}&city=`
//搜索目标城市天气
export const serachWeather = (adcode) => {
  const data = axios
    .get(url + adcode + '&extensions=all')
    .then((res) => {
      return res.data.forecasts[0].casts
    })
    .catch(() => {
      return 404
    })
  return data
}
//获取指定城市天气
export const getCityWeather = async (adcode) => {
  const res = await axios
    .get(url + adcode)
    .then((res) => {
      return res.data.lives[0]
    })
    .catch(() => {
      return 404
    })
  return res
}
//获取当前城市实时天气
export const getTodayWeather = async () => {
  const data = await axios
    .get('https://restapi.amap.com/v3/ip?key=b0ed3d91a25e8351ac877bd6c133e160')
    .then((res) => {
      return res.data.adcode
    })
    .catch(() => {
      return 404
    })
  if (data != 404) {
    const res = await axios
      .get(url + data)
      .then((res) => {
        return res.data.lives[0]
      })
      .catch(() => {
        return 404
      })
    return res
  } else {
    return data
  }
}
//获取城市编码
export const getadcode = (str) => {
  const data = axios
    .get(`https://restapi.amap.com/v3/geocode/geo?key=${key}&address=${str}`)
    .then((res) => {
      if (res.data.geocodes) {
        return res.data.geocodes[0]
      } else {
        return ''
      }
    })
    .catch(() => {
      return 404
    })
  return data
}
